source("functions.R")
source("models.R")

events <- yaml::read_yaml("events.yml")

local({
    dat <- cbind(readRDS("data_lss_ja.RDS"), 
                 readRDS("data_newsmap_ja.RDS"), 
                 readRDS("data_dictionary_ja.RDS"))
    dat <- subset(dat, class %in% c("kp", "jp") & date <= as.Date("2018-12-31"))
    term <- "publicationyomiuri:legislation3"
    
    result <- data.frame()
    for (w in c(30, 60, 90, 120)) {
        temp <- flag_events(dat, events$JP, w)
        for (i in seq(1000)) {
            cat(w, i, "\n")
            e <- events$JP
            e$legislation <- as.list(sample(temp$date, 4))  # 4 legislative events
            temp <- flag_events(temp, e, w, merge = FALSE)
            summ <- summary(lm(f5, temp))
            if (term %in% rownames(summ$coefficients)) {
                result <- rbind(result, data.frame(
                    window = w,
                    i = i, 
                    beta = summ$coefficients[term, 1],
                    t = summ$coefficients[term, 3],
                    r2 = summ$r.squared)
                )
            } else {
                result <- rbind(result, data.frame(
                    window = w, i = i, beta = NA, t = NA, r2 = summ$r.squared)
                )
            }
        }
    }
    saveRDS(result, "data_bootstrap_ja.RDS")
})


local({
    dat <- cbind(readRDS("data_lss_he.RDS"), 
                 readRDS("data_newsmap_he.RDS"), 
                 readRDS("data_dictionary_he.RDS"))
    dat <- subset(dat, class %in% c("il", "ir") & date <= as.Date("2018-12-31"))
    term <- "publicationyedioth:election3"
    
    result <- data.frame()
    for (w in c(30, 60, 90, 120)) {
        temp <- flag_events(dat, events$IL, w)
        for (i in seq(1000)) {
            cat(w, i, "\n")
            e <- events$IL
            e$election <- as.list(sample(temp$date, 3)) # 3 electoral events
            temp <- flag_events(temp, e, w, merge = FALSE)
            summ <- summary(lm(f5, temp))
            if (term %in% rownames(summ$coefficients)) {
                result <- rbind(result, data.frame(
                    window = w,
                    i = i, 
                    beta = summ$coefficients[term, 1],
                    t = summ$coefficients[term, 3],
                    r2 = summ$r.squared)
                )
            } else {
                result <- rbind(result, data.frame(
                    window = w, i = i, beta = NA, t = NA, r2 = summ$r.squared)
                )
            }
        }
    }
    saveRDS(result, "data_bootstrap_he.RDS")
})
